Page({
  data: {
    dataList: [], // 订单列表数据
    isLoading: false, // 加载状态
    pageNo: 1, // 当前页码
    pageSize: 5, // 每页条数
    hasMore: true, // 是否有更多数据
    currentFilter: 'all', // 当前筛选类型
    currentStatus: '', // 当前筛选的orderStatus
    showActionSheet: false, // 操作弹窗显示状态
    showRatingModal: false, // 评价模态框显示状态
    currentOrder: null, // 当前点击的订单
    actionButtons: [], // 动态生成的操作按钮
    rating: 0, // 当前选中的星级（1-5）
    pj: 0,  // 提交给后端的评分参数（1=好评，2=中评，3=差评）
    comment: '' // 评价内容
  },

  onLoad: function (options) {
    if (options.filter) {
      let status = '';
      switch (options.filter) {
        case 'received':
          status = '2';
          break;
        case 'processing':
          status = '3';
          break;
        case 'completed':
          status = '4';
          break;
      }
      this.setData({
        currentFilter: options.filter,
        currentStatus: status
      });
    }
    this.fetchOrderList();
  },

  onShow: function () {
    if (this.data.dataList.length === 0) {
      this.setData({
        pageNo: 1,
        hasMore: true
      });
      this.fetchOrderList();
    }
  },

  onPullDownRefresh: function () {
    this.setData({ pageNo: 1 });
    this.fetchOrderList(true);
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.isLoading) {
      this.setData({ pageNo: this.data.pageNo + 1 });
      this.fetchOrderList();
    }
  },

  handleFilter: function (e) {
    const newType = e.currentTarget.dataset.type;
    const newStatus = e.currentTarget.dataset.status;

    if (this.data.currentFilter === newType) return;

    wx.showLoading({ title: '加载中...', mask: true });
    this.setData({
      currentFilter: newType,
      currentStatus: newStatus,
      pageNo: 1,
      dataList: [],
      hasMore: true
    }, () => {
      this.fetchOrderList().then(() => wx.hideLoading()).catch(() => wx.hideLoading());
    });
  },

  openActionSheet(e) {
    const order = e.currentTarget.dataset.order;
    
    if (!order) {
      wx.showToast({ title: '获取订单信息失败', icon: 'none' });
      return;
    }
    
    // 打印已完成订单的orderId
    if (order.orderStatus === 4) {
      console.log('已完成订单的orderId：', order.orderId);
    }

    let actionButtons = [];
    switch (order.orderStatus) {
      case 1: // 待服务
        actionButtons = [{ text: '撤回订单', action: 'withdraw' }];
        break;
      case 2: // 已接单
      case 3: // 进行中
        actionButtons = [{ text: '申请撤回订单', action: 'applyWithdraw' }];
        break;
      case 4: // 已完成
        actionButtons = order.isEvaluated 
          ? [{ text: '查看评价', action: 'viewRating' }]
          : [{ text: '评价', action: 'rate' }];
        actionButtons.push({ text: '投诉', action: 'complain' });
        break;
    }

    this.setData({
      showActionSheet: true,
      currentOrder: order,
      actionButtons: actionButtons
    });
  },

  closeActionSheet() {
    this.setData({ showActionSheet: false });
  },

  handleActionClick(e) {
    const action = e.currentTarget.dataset.action;
    const order = this.data.currentOrder;
    const userInfo = wx.getStorageSync('userInfo');

    if (!userInfo?.userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    if (!order) {
      wx.showToast({ title: '获取订单信息失败', icon: 'none' });
      this.closeActionSheet();
      return;
    }

    // 撤回订单
    if (action === 'withdraw') {
      wx.showModal({
        title: '提示',
        content: `确定要撤回订单【${order.orderNo || ''}】吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '处理中...', mask: true });
            this.updateOrderStatus({
              id: order.orderId,
              status: 5
            });
          }
        }
      });
    }

    // 申请撤回订单
    if (action === 'applyWithdraw') {
      wx.showModal({
        title: '提示',
        content: `确定要申请撤回订单【${order.orderNo || ''}】吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '提交中...', mask: true });
            this.updateOrderStatus({
              id: order.orderId,
              status: 6
            });
          }
        }
      });
    }

    // 投诉功能
    if (action === 'complain') {
      wx.navigateTo({ url: `/pages/complain/complain?orderId=${order.orderId}` });
      this.closeActionSheet();
    }

    // 打开评价模态框
    if (action === 'rate') {
      this.setData({
        showRatingModal: true,
        rating: 0,
        pj: 0,
        comment: ''
      });
      this.closeActionSheet();
    }

    // 查看评价
    if (action === 'viewRating') {
      wx.showModal({
        title: '订单评价',
        content: `评分：${this.renderStars(order.pj)}\n评价：${order.comment || '无'}`,
        showCancel: false
      });
      this.closeActionSheet();
    }
  },

  // 渲染星级
  renderStars(pj) {
    let stars = '';
    let starCount = 0;
    
    if (pj === 1) starCount = 5;    // 好评 → 5星
    else if (pj === 2) starCount = 3; // 中评 → 3星
    else if (pj === 3) starCount = 1; // 差评 → 1星

    for (let i = 1; i <= 5; i++) {
      stars += i <= starCount ? '★' : '☆';
    }
    return stars;
  },

  // 选择星级时打印参数
  selectStar(e) {
    const rating = e.currentTarget.dataset.rating;
    let pj = 0;
    
    if (rating === 5) {
      pj = 1; // 5星 → pj=1（好评）
    } else if (rating >= 2 && rating <= 4) {
      pj = 2; // 2-4星 → pj=2（中评）
    } else if (rating === 1) {
      pj = 3; // 1星 → pj=3（差评）
    }

    // 打印选中的星级和对应的参数
    console.log(`选中${rating}星，对应后端参数pj=${pj}`);

    this.setData({ 
      rating,
      pj
    });
  },

  // 输入评价内容
  inputComment(e) {
    this.setData({ comment: e.detail.value });
  },

  // 提交评价
  submitRating() {
    if (!this.data.currentOrder) {
      wx.showToast({ title: '订单信息丢失，请重新选择', icon: 'none' });
      this.setData({ showRatingModal: false });
      return;
    }

    if (this.data.rating === 0) {
      wx.showToast({ title: '请选择评分', icon: 'none' });
      return;
    }

    const order = this.data.currentOrder;
    if (!order.orderId || isNaN(Number(order.orderId))) {
      wx.showToast({ title: '订单ID无效', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '提交中...', mask: true });

    wx.request({
      url: 'http://localhost:8080/orders/updatepj',
      method: 'PUT',
      data: {
        orderId: Number(order.orderId),
        pj: this.data.pj
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 201) {
          wx.showToast({ title: '评价成功', icon: 'success' });
          this.setData({ showRatingModal: false });
          // 刷新订单列表（会更新isEvaluated状态）
          this.setData({ pageNo: 1, dataList: [] }, () => this.fetchOrderList());
        } else {
          wx.showToast({ title: `评价失败: ${res.data?.msg || '服务器错误'}`, icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
        console.error('评价提交失败:', err);
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 关闭评价模态框
  closeRatingModal() {
    this.setData({ showRatingModal: false });
  },

  // 更新订单状态接口
  updateOrderStatus(params) {
    wx.request({
      url: 'http://localhost:8080/orders/updataStatus',
      method: 'PUT',
      data: params,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 201) {
          wx.showToast({ title: '操作成功', icon: 'success' });
          this.setData({ pageNo: 1, dataList: [] }, () => this.fetchOrderList());
        } else {
          wx.showToast({ title: '操作失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      },
      complete: () => {
        wx.hideLoading();
        this.closeActionSheet();
      }
    });
  },

  // 获取订单列表
  fetchOrderList: function (isRefresh = false) {
    return new Promise((resolve, reject) => {
      if (this.data.isLoading) {
        resolve();
        return;
      }

      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo?.userId) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        this.setData({ isLoading: false });
        reject('未获取到用户信息');
        return;
      }

      this.setData({ isLoading: true });
      const params = {
        userId: userInfo.userId,
        pageNo: this.data.pageNo,
        pageSize: this.data.pageSize
      };
      if (this.data.currentStatus !== '') {
        params.orderStatus = this.data.currentStatus;
      }

      wx.request({
        url: 'http://localhost:8080/orders/list',
        method: 'GET',
        data: params,
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200 && res.data.data) {
            const outerData = res.data;
            const innerData = outerData.data;
            if (innerData && innerData.code === 200 && innerData.data) {
              const responseData = innerData.data;
              const newDataList = responseData.dataList || [];
              const totalCount = responseData.totalCount || 0;

              const currentDataList = isRefresh ? newDataList : [...this.data.dataList, ...newDataList];
              this.setData({
                dataList: currentDataList,
                hasMore: currentDataList.length < totalCount
              });
              resolve();
            } else {
              wx.showToast({ title: '暂无数据', icon: 'none' });
              reject();
            }
          } else {
            wx.showToast({ title: '获取数据失败', icon: 'none' });
            reject();
          }
        },
        fail: () => {
          wx.showToast({ title: '网络请求失败', icon: 'none' });
          reject();
        },
        complete: () => {
          this.setData({ isLoading: false });
          if (isRefresh) wx.stopPullDownRefresh();
        }
      });
    });
  }
});